import * as THREE from "three"
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"
import { OrbitControls } from "three/addons/controls/OrbitControls.js"
import modelTest from "./model.js"
const loadGlb = async (path) => {
  const loader = new GLTFLoader()
  return new Promise((res, rej) => {
    loader.load(
      path,
      function (gltf) {
        res(gltf)
      },
      undefined,
      function (error) {
        rej(error)
        console.error(error)
      }
    )
  })
}
const animateFN = (fn = () => {}) => {
  function animate() {
    requestAnimationFrame(animate)
    fn()
  }
  animate()
}
export const render = async (dom) => {
  dom.style.overflow = "hidden"
  const scene = new THREE.Scene()
  scene.background = new THREE.Color("pink") // 玫瑰色背景
  const camera = new THREE.PerspectiveCamera(
    90,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  )
  console.log(devicePixelRatio)
  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
  scene.add(modelTest)
  const renderer = new THREE.WebGLRenderer({
    antialias: true,
  })
  renderer.setPixelRatio(window.devicePixelRatio)
  renderer.setSize(window.innerWidth, window.innerHeight)
  dom.appendChild(renderer.domElement)
  const controls = new OrbitControls(camera, renderer.domElement)
  controls.addEventListener("change", function (params) {
    // renderer.render(scene, camera)
    console.log("数据 位置变化", params)
  })
  camera.position.z = 5
  const light = new THREE.PointLight(0xffffff, 2.0)
  const light1 = new THREE.AmbientLight(0xffffff, 0.5)
  light.decay = 0.0
  light.position.set(200, 200, 100)
  scene.add(light)
  scene.add(light1)
  const gift = await loadGlb("/gift_box.glb")
  const model = gift.scene
  scene.add(model)
  window.addEventListener("resize", () => {
    // 设置画布尺寸
    renderer.setSize(window.innerWidth, window.innerHeight)
    // 设置相机宽高比
    camera.aspect = window.innerWidth / window.innerHeight
    // 更新相机投影矩阵属性
    camera.updateProjectionMatrix()
  })
  animateFN(() => {
    model.rotation.y += 0.01
    renderer.render(scene, camera)
  })
}
